﻿using Himp.Platform.Apps;
using IdentityModel;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;

namespace Himp.Platform
{
    public class LogProjectService : LogBaseService
    {
        private IHttpClientFactory _httpClientFactory;
        private ILogger<LogProjectService> _logger;
        private string _projectUrl = "/api/v2/projects";

        /// <summary>
        /// , ConnectionMultiplexer redis
        /// </summary>
        /// <param name="httpClientFactory"></param>
        /// <param name="logger"></param>
        public LogProjectService(IHttpClientFactory httpClientFactory, ILogger<LogProjectService> logger) :
            base(httpClientFactory, logger)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
        }

        public async Task<PagedResultDto<LogProjectDto>> GetListAsync()
        {
            var token = await Login();
            var client = _httpClientFactory.CreateClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            StringBuilder dataUrlSB = new StringBuilder();
            dataUrlSB.Append(_baseUrl);
            dataUrlSB.Append(_projectUrl);
            var eventDataResponseModel = await client.GetAsync(dataUrlSB.ToString());

            if (eventDataResponseModel.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var logProjects = await eventDataResponseModel.Content.ReadFromJsonAsync<List<LogProjectDto>>();

                return new PagedResultDto<LogProjectDto>(logProjects.Count, logProjects);
            }
            else
            {
                throw new AbpException("获取日志数据失败");
            }
        }
    }
}
